#财务数据统计服务类  flydragon
class StatisticalDatum::FinanceIncomeTypeService
  include HeiPisService

  #company 单位
  #studio 分店
  def initialize(company, studio)
    @company = company
    @studio = studio
  end


  #执行方法 返回值
  def call

    #=======最近30天数据=======#
    #时间数组
    income_type_infos = {}

    # 主营业务(订单+工作室维护) 
    # 营业外收入 其他收入(工作室维护)
    income_types = %w(主营业务收入 营业外收入 其他业务收入)

    income_types.each{|type|
      income_type_infos[type] = {:value => 0, name: type}
    }

    start_date = Date.new(Date.current.year, 1)
    end_date = Time.now

    
    # 获取手动维护的收入信息
    finance_type_info = finance_type(start_date,end_date)
    # 获取订单收入
    income_type_infos["主营业务收入"][:value] = order_income(start_date,end_date) + (finance_type_info["主营业务收入"]||=0)
    income_type_infos["营业外收入"][:value] = finance_type_info["营业外收入"] if finance_type_info["营业外收入"].present? 
    income_type_infos["其他业务收入"][:value] = finance_type_info["其他业务收入"] if finance_type_info["其他业务收入"].present? 

    income_type_infos
  end


  # 获取订单的收入
  def order_income(start_date,end_date)

    filter_params = {:company_id => @company.id,:start_date => start_date,:end_date => end_date}

    sql = %Q{
      select sum(ord.total_price) as total_amount
      from orders ord join studios on ord.studio_id = studios.id
      where studios.company_id = :company_id 
      and (ord.created_at between :start_date and :end_date) 
    }

    data = 0
    # 获取订单收入
    Order.find_by_sql([sql,filter_params]).each do |record|
      data = record.total_amount||=0
    end
    data
  end


  # 获取工作室手动维护的收入
  def finance_type(start_date,end_date)

    filter_params = {:company_id => @company.id,:start_date => start_date,:end_date => end_date}
    
    # 获取录入收入
    sql = %Q{
      
      select sum(amount) as total_amount,finance_category  
      from finances 
      where company_id = :company_id 
      and is_system = 0
      and (setdate between :start_date and :end_date) 
      and finance_type = '收入'
      group by finance_category
    }

    data = {}
    Finance.find_by_sql([sql,filter_params]).each do |record|

      data[record.finance_category] = record.total_amount||=0
    end
    data
  end

end
